<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <!-- 吃苹果的最大数目 -->
    <script>
      var eatenApples = function (apples, days) {
        let d = 0
        let max = 0
        for (let i = 0; i < days.length; i++) {
          d = Math.max(d, i + days[i])
        }
        //最多可以吃到第d天
        let arr = new Array(d).fill(0)
        //倒着吃
        let len = days.length - 1
        for (let i = len; i >= 0; i--) {
          //可以吃n个苹果
          let n = Math.min(apples[i], days[i])
          //最迟第m天吃
          let m = days[i] + i
          //从第m天开始吃，一天只吃一个
          let t = 1
          while (m > i) {
            if (arr[m - 1] == 0 && t <= n) {
              arr[m - 1]++
              m--
              t++
            } else {
              m--
            }
          }
        }
        let y = 0
        let z = d
        while (z >= 0) {
          if (arr[z - 1] == 0) y++
          z--
        }
        return d - y
      }
      console.log(eatenApples([3, 0, 0, 0, 0, 2], [3, 0, 0, 0, 0, 2]))
    </script>
  </body>
</html>
